package com.captjack.common.util.http;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;

/**
 * @author Capt Jack
 * @date 2018/6/1
 */
public enum HttpConnectionPollManager {

    /**
     * 连接管理
     */
    HTTP();

    /**
     * apache-http工具连接池管理类
     */
    private PoolingHttpClientConnectionManager poolingHttpClientConnectionManager;

    /**
     * 初始化连接
     */
    HttpConnectionPollManager() {
        this.poolingHttpClientConnectionManager = createConnectionPool();
    }

    /**
     * 创建http连接池管理
     *
     * @return http连接池管理
     */
    private PoolingHttpClientConnectionManager createConnectionPool() {
        // 返回结果
        PoolingHttpClientConnectionManager manager = null;
        try {
            // 安全管理
            SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
            // 加载信任管理
            sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            // 连接端口工厂
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build());
            // http连接设置
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("https", sslConnectionSocketFactory)
                    .register("http", new PlainConnectionSocketFactory())
                    .build();
            manager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            // 最大连接数
            manager.setMaxTotal(100);
            // 单路由最大连接数
            manager.setDefaultMaxPerRoute(80);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return manager;
    }

    /**
     * @return httpClient请求客户端
     */
    public CloseableHttpClient getHttpsClient() {
        return HttpClients.
                custom().
                setDefaultRequestConfig(RequestConfig.custom().setCircularRedirectsAllowed(true).build()).
                setConnectionManager(this.poolingHttpClientConnectionManager).
                build();
    }

}
